package service;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import enums.MenuType;
import model.Menu;

public class MenuService extends BaseService {
	public Ret save(Menu menu) {
		if (menu.isRepeatName()) {
			return fail("菜单已添加") ;
		}
		long parentId = null == menu.getParentId() ? 0L : menu.getParentId() ;
		menu.setParentId(parentId);
		menu.setMaxOrderNum();
		Long menuId = menu.getId();
		if(null == menuId) {
			menu.save();
		}else {
			menu.update();
		}
		return Ret.ok();
	}
	
	/**
	 * 删除时，判断菜单下面有没有子菜单，有子菜单提示不能删除
	 * @param id
	 * @return
	 */
	public Ret delete(Long id) {
		Long count = Menu.dao.CountByParentId(id) ;
		return count > 0 ? fail("该菜单下有子菜单不能删除") : Menu.dao.deleteById(id) ? ok() : fail() ;
	}

	public List<Record> getAllMenu() {
		return Db.find("SELECT tm.* , tmp.name AS parentName FROM t_menu tm LEFT JOIN t_menu tmp ON tmp.id = tm.parentId ORDER BY tmp.orderNum, tm.orderNum");
	}
	
	public List<Record> listAll() {
		List<Record> list = Db.find("SELECT * FROM t_menu ORDER BY parentId, orderNum");
		for (Record record : list) {
			record.set("typeName", MenuType.getTitleByValue(record , "type"));
		}
		return list ;
	}
	
	public List<Menu> getParentList(Menu menu) {
		if (null == menu || menu.getType() == MenuType.getLevelOne()) {
			return new ArrayList<Menu>();
		}
		return Menu.dao.findByType( menu.getType() - 1);
	}
	
	public List<Menu> getParentList(int type) {
		return Menu.dao.findByType( type - 1);
	}
}
